package com.c.service.admin;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.pool.DruidDataSource;

import cn.hutool.core.date.DateTime;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;

@Service
public class UploadExcelService {

	@Autowired
	private DruidDataSource ds;

	public void saveData(MultipartFile multifile) {
		Session session = Session.create(ds);
		ExcelReader reader = null;
		try {
			session.beginTransaction();
			reader = ExcelUtil.getReader(multifile.getInputStream());
			List<List<Object>> readAll = reader.read();
			for (int i = 1; i < readAll.size(); i++) {
				List<Object> row = readAll.get(i);

				if (row.size() > 3) {
					Digester md5 = new Digester(DigestAlgorithm.MD5);
					String digestHex = md5.digestHex("" + row.get(1) + row.get(2) + row.get(3));
					Entity entity = Entity.create("data").set("number", row.get(0) + "").set("name", row.get(1) + "")
							.set("money", row.get(2) + "").set("year", row.get(3) + "").set("md5", digestHex);
					session.insert(entity);
				}
			}
			Entity log = Entity.create("log").set("create_time", new DateTime(new Date()).toString())
					.set("operation", "入库数据数量:" + (readAll.size() - 1)).set("operator", "管理员");
			session.insert(log);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.quietRollback();
		}
	}

}
